/**
 * 
 */
package user.service.impl;

import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.alibaba.dubbo.config.annotation.Service;

import user.dao.mapper.IUserMapper;
import user.entity.User;
import user.service.IUserService;

/**
 * @author Eric
 */
@Service
public class UserService implements IUserService {

	@Autowired
	IUserMapper userMapper;
	
	private long extendTime = 36000000l;  //一个小时
	
	@Override
	public boolean isExpiredToken(String token) {
		User user = userMapper.findByToken(token);
		Assert.notNull(user, "this token [" + token + "] is not user found.");
		
		long expiredTime = user.getExpiredTime();
		
		if(expiredTime >= System.currentTimeMillis()) {
			//未过期   刷新过期时间
			Assert.isTrue(userMapper.updateExpiredTime(user.getUserId(), System.currentTimeMillis() + extendTime) != 0, "extendTime extend failtal");
			return true;
		} else {
			//过期
			return false;
		}
	}

	@Override
	public boolean extendToken(String token, long extendTime) {
		User user = userMapper.findByToken(token);
		Assert.isTrue(userMapper.updateExpiredTime(user.getUserId(), System.currentTimeMillis() + extendTime) != 0, "extendTime extend failtal");
		return true;
	}

	@Override
	public User login(String phone, String password) {
		Integer userId = userMapper.auth(phone, password);
		
		if(userId != null) {
			//此处为登录成功  应该生成token  保存到数据库  并且件用户信息返回给登录者。
			String token = generateToken(userId);
			userMapper.updateToken(userId, token);
			userMapper.updateExpiredTime(userId, System.currentTimeMillis() + extendTime);
			User user = userMapper.findById(userId);
			user.setPassword("");  //密码不返回
			return user;
		} else {
			return null;
		}
	}

	@Override
	public void logout(Integer userId) {
		//用户退出，将token的过期时间设置为当前时间
		userMapper.updateExpiredTime(userId, System.currentTimeMillis());
	}

	@Override
	public User userInfo(Integer userId) {
		return userMapper.findById(userId);
	}
	
	//生成token
	private String generateToken(Integer userId) {
		StringBuilder sb = new StringBuilder();
		sb.append(userId)
		.append(RandomStringUtils.random(8))
		.append(UUID.randomUUID().toString());
		String token = Base64.encodeBase64URLSafeString(DigestUtils.md5(sb.toString()));
		return token;
	}

	@Override
	public void regist(String phone, String password) {
		userMapper.save(User.builder().password(password).phone(phone).build());
	}

}
